{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "ef84349a",
      "metadata": {
        "vscode": {
          "languageId": "shellscript"
        }
      },
      "source": [
        "基于 Anaconda 创建python 数据分析 环境\n",
        "conda create -n myenv python=3.10 pandas jupyter seaborn scikit-learn keras tensorflow\n",
        " 激活myenv\n",
        "conda activate myenv\n",
        "\n",
        " 删除k\n",
        "conda deactivate\n",
        "\n",
        "在环境中安装包的时候需要先激活\n",
        "conda activate myenv\n",
        "conda install conda-forge::langchain-community\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b9d18e1d",
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "import numpy as np\n",
        "data = pd.read_csv('titanic3.csv')\n",
        "\n",
        "# 数据集异常值处理\n",
        "data.replace('?', np.nan, inplace= True)\n",
        "data = data.astype({\"age\": np.float64, \"fare\": np.float64})\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e8fb2244",
      "metadata": {},
      "source": [
        " 提示：vscode 要添加新单元格，您可以使用现有单元格左下角的插入单元格图标。或者，您也可以使用 Esc 进入命令模式，然后按 B 键。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "df91ac75",
      "metadata": {},
      "outputs": [],
      "source": [
        "import seaborn as sns\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "fig, axs = plt.subplots(ncols=5, figsize=(30,5))\n",
        "sns.violinplot(x=\"survived\", y=\"age\", hue=\"sex\", data=data, ax=axs[0])\n",
        "sns.pointplot(x=\"sibsp\", y=\"survived\", hue=\"sex\", data=data, ax=axs[1])\n",
        "sns.pointplot(x=\"parch\", y=\"survived\", hue=\"sex\", data=data, ax=axs[2])\n",
        "sns.pointplot(x=\"pclass\", y=\"survived\", hue=\"sex\", data=data, ax=axs[3])\n",
        "sns.violinplot(x=\"survived\", y=\"fare\", hue=\"sex\", data=data, ax=axs[4])\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "36940963",
      "metadata": {},
      "outputs": [],
      "source": [
        "data.replace({'male': 1, 'female': 0}, inplace=True)\n",
        "\n",
        "# 计算相关性\n",
        "data.corr(numeric_only=True).abs()[[\"survived\"]]\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "5cb4c548",
      "metadata": {},
      "outputs": [],
      "source": [
        "#  新增一个列\n",
        "data['relatives'] = data.apply (lambda row: int((row['sibsp'] + row['parch']) > 0), axis=1)\n",
        "data.corr(numeric_only=True).abs()[[\"survived\"]]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "204a8ed5",
      "metadata": {},
      "outputs": [],
      "source": [
        "#完成训练集的选择\n",
        "data = data[['sex', 'pclass','age','relatives','fare','survived']].dropna()\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "9ab362cd",
      "metadata": {},
      "outputs": [],
      "source": [
        "from sklearn.model_selection import train_test_split\n",
        "#使用sklearn 方法完成训练集和验证集的拆分\n",
        "x_train, x_test, y_train, y_test = train_test_split(data[['sex','pclass','age','relatives','fare']], data.survived, test_size=0.2, random_state=0)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "5cfed2f2",
      "metadata": {},
      "outputs": [],
      "source": [
        "from sklearn.preprocessing import StandardScaler\n",
        "\n",
        "# 规范化输入\n",
        "sc = StandardScaler()\n",
        "X_train = sc.fit_transform(x_train)\n",
        "X_test = sc.transform(x_test)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "ae955d52",
      "metadata": {},
      "outputs": [],
      "source": [
        "from sklearn.naive_bayes import GaussianNB\n",
        "#建模 朴素贝叶斯算法\n",
        "model = GaussianNB()\n",
        "model.fit(X_train, y_train)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "38270b15",
      "metadata": {},
      "outputs": [],
      "source": [
        "\n",
        "from sklearn import metrics\n",
        "\n",
        "#使用验证集评估模型\n",
        "predict_test = model.predict(X_test)\n",
        "print(metrics.accuracy_score(y_test, predict_test))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a61bb7fd",
      "metadata": {},
      "source": [
        "以下内容时神经网络"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "5df2b97e",
      "metadata": {},
      "outputs": [],
      "source": [
        "from keras.models import Sequential\n",
        "from keras.layers import Dense\n",
        "# 顺序神经网络\n",
        "model = Sequential()\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "c7614fb0",
      "metadata": {},
      "outputs": [],
      "source": [
        "model.add(Dense(5, kernel_initializer = 'uniform', activation = 'relu', input_dim = 5))\n",
        "model.add(Dense(5, kernel_initializer = 'uniform', activation = 'relu'))\n",
        "model.add(Dense(1, kernel_initializer = 'uniform', activation = 'sigmoid'))\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b15883bd",
      "metadata": {},
      "outputs": [],
      "source": [
        "model.summary()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "572ffcca",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 模型训练\n",
        "model.compile(optimizer=\"adam\", loss='binary_crossentropy', metrics=['accuracy'])\n",
        "model.fit(X_train, y_train, batch_size=32, epochs=50)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "3bd8b61e",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 验证集验证\n",
        "y_pred = np.rint(model.predict(X_test).flatten())\n",
        "print(metrics.accuracy_score(y_test, y_pred))\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "myenv",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}